package model

import (
	"encoding/json"
	"gorm.io/gorm/clause"
	"server/common"
	"server/pkg/app"
)

type HisTask struct {
	Model
	Status   string `gorm:"column:status;not null;type:varchar(16);" json:"status"`
	StopTime string `gorm:"column:stoptime;type:varchar(25)" json:"stoptime"`
	BaseTask

	RunWay string `json:"runway"`
	Branch string `gorm:"column:branch;not null;type:varchar(32);default:main" json:"branch"`

	OwnerID int   `json:"owner_id"`
	Owner   Owner `gorm:"references:ID"`

	ProjectID int     `json:"project_id"`
	Project   Project `gorm:"references:ID"`

	Env json.RawMessage `gorm:"column:env;type:json" json:"env"`

	TaskGroupStr json.RawMessage `gorm:"column:taskgroups;type:json"`
	Param        json.RawMessage `gorm:"column:param;type:json"`

	TaskGroups []TaskGroup `json:"taskgroup"`
}

func (histask HisTask) TableName() string {
	return "histask"
}

func (task *HisTask) Create() error {
	if err := common.DB.Create(&task).Error; err != nil {
		return err
	}
	return nil
}

func (task *HisTask) List(page *app.Page) ([]HisTask, int64) {
	tasks := []HisTask{}
	var count int64
	if err := common.DB.Preload(clause.Associations).Order("id desc").Limit(page.Size).Offset((page.Page - 1) * page.Size).Find(&tasks).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
		return tasks, count
	}
	return tasks, count
}

func (task *HisTask) Update() error {
	if err := common.DB.Where("id = ?", task.ID).Updates(&task).Error; err != nil {
		return err
	}
	return nil
}
